<template>
  <div>
    <div class="pl10 pr10">
      <a-tabs v-model="tab" @tabClick="tabClick">
        <a-tab-pane v-for="item in formInfo.formList" :key="item.viewId" :tab="item.formName"></a-tab-pane>
        <div slot="tabBarExtraContent" class="flx-e">
          <ZgSwitch
            class="pos-rlt t10"
            v-if="hasPdf"
            :width="80"
            v-model="showForm"
            :text="['表单视图', 'PDF视图']"
          ></ZgSwitch>
        </div>
      </a-tabs>
      <a-row :gutter="10">
        <a-col :span="21">
          <Pdf v-if="formView.state == 3" :pdfUrl="pdfUrl"></Pdf>
          <div v-else>
            {{ formView.state }}
            <Readonly ref="Readonly" v-if="formView.state == 2" :formView="formView"></Readonly>
            <div v-if="formView.state == 1" style="background: #f6f6f6">
              <ZgForm ref="ZgForm" v-model="formObj" :formView="formView" :saveUrl="saveUrl" @ok="submit"></ZgForm>
            </div>
          </div>
        </a-col>
        <a-col :span="3">
          <ZgDataSelect></ZgDataSelect>
          <ZgDataSelect></ZgDataSelect>
          <a-button
            type="default"
            v-if="showForm && !hasPdf"
            class="wfull mb10"
          ><i class="fa fa-file-text-o mr5" />保存草稿</a-button
          >
          <a-button
            type="primary"
            v-if="formView.state == 1"
            class="wfull mb10"
            @click="save"
          ><i class="fa fa-save mr5" />保存单据</a-button
          >
          <a-button
            type="primary"
            v-if="formView.state == 2 || formView.state == 3"
            class="wfull mb10"
            @click="reEdit"
          ><i class="fa fa-edit mr5" />重新编辑</a-button
          >
          <a-button
            type="primary"
            v-if="formView.state == 2"
            class="wfull mb10"
            @click="createPdf"
          ><i class="fa fa-file mr5" />生成文件</a-button
          >
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import Pdf from './Pdf'
import Readonly from './Readonly'
export default {
  components: {
    Pdf,
    Readonly
  },
  props: {
    formInfo: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    formInfo: {
      handler (newVal) {
        if (newVal && Array.isArray(newVal.formList) && newVal.formList.length > 0) {
          // 如果是第一次加载（tab为空），则设置为第一个页签
          if (!this.tab) {
            this.tab = newVal.formList[0].viewId
            this.formView.active = newVal.formList[0].viewId
          }
          // 否则保持当前页签，只更新formView
          this.fetchFormView(newVal)
        }
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      tab: '',
      showForm: true,
      hasSave: false,
      hasPdf: false,
      formObj: {},
      formView: {},
      pdfUrl: '',
      saveUrl: ''
    }
  },
  methods: {
    fetchFormView (newVal) {
      const form = newVal.formList.filter((item) => item.viewId === this.tab)[0]
      const newFormView = newVal.bizFormDetail.filter((item) => item.formId === form.formId)[0]

      // 使用 Vue.set 或 Object.assign 确保响应式更新
      this.formView = Object.assign({}, newFormView, { active: form.viewId })

      if (this.formView.bizFormId) {
        this.saveUrl = '/zg-autoform/table/data/form/update/'
      } else {
        this.saveUrl = '/zg-autoform/table/data/form/add/'
      }
    },
    tabClick (val) {
      this.tab = val
      this.fetchFormView(this.formInfo)
      this.$emit('tabClick', val)

      // 如果当前是Readonly模式，需要更新Readonly组件
      if (this.$refs.Readonly) {
        this.$nextTick(() => {
          this.tryInitReadonly()
        })
      }
    },
    save () {
      this.$refs.ZgForm.save()
      // this.$emit('save', obj)
    },
    tryInitReadonly () {
      let attempts = 0
      const maxAttempts = 20
      const tryInit = () => {
        attempts++

        if (this.$refs.Readonly && this.$refs.Readonly.initData) {
          this.$refs.Readonly.initData()
          return
        }

        if (attempts < maxAttempts) {
          setTimeout(tryInit, 100)
        }
      }
      this.$nextTick(() => {
        tryInit()
      })
    },
    submit (res) {
      if (res) {
        const obj = {
          bizFormId: this.formView.id,
          businessId: res,
          is_seal: '',
          printData: {}
        }

        this.$http.post('/zg-autoflow/flow/workflowManage/saveData', obj, (res) => {
          // this.hasPdf = false
          // this.showForm = true
          // this.hasSave = true
          this.$message.success('保存成功')
          // 等待Vue响应式更新完成后再尝试初始化
          this.tryInitReadonly()
          this.$emit('save', res)
        })
      } else {
        this.$message.success('保存成功')
        this.formView.state = 2
        // 等待Vue响应式更新完成后再尝试初始化
        this.$nextTick(() => {
          this.tryInitReadonly()
          this.$emit('save', this.formView)
        })
      }
    },
    reEdit () {
      this.formView.state = 1
      this.formView.active = this.tab
    },
    createPdf () {
      this.$http.post('/zg-autoflow/flow/workflowManage/makePdf', { bizFormId: this.formView.id }, res => {
        this.formView = res
        // this.pdfUrl = process.env.VUE_APP_MINIO_PROXY + res.pdfFilePath
        this.pdfUrl = 'https://zfjsfile.sxccol.com/malan/20231114/8LE19ANh.pdf'
        console.log(this.pdfUrl, '--------')
        this.$emit('createPdf', this.formObj, this.pdfUrl)
      })
    }
  }
}
</script>

<style scoped>
</style>
